package com.chcit.mobile.mvp.shipment.fragment;

import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.GravityEnum;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.chcit.custom.view.loader.QuickLoader;
import com.xuexiang.xui.widget.spinner.editspinner.EditSpinner;
import com.chcit.custom.view.text.AutofitTextView;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.BuildConfig;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.di.module.CommonModule;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.entity.Locator;
import com.chcit.mobile.mvp.entity.MonitorCode;
import com.chcit.mobile.mvp.entity.ShipmentBean;
import com.chcit.mobile.mvp.common.adapter.MonitorCodeAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.chcit.mobile.di.component.DaggerShipmentDetailComponent;
import com.chcit.mobile.di.module.ShipmentDetailModule;
import com.chcit.mobile.mvp.shipment.contract.ShipmentDetailContract;
import com.chcit.mobile.mvp.shipment.presenter.ShipmentDetailPresenter;
import com.chcit.mobile.R;
import com.xuexiang.xui.widget.toast.XToast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 采购出库详情页面
 */
public class ShipmentDetailFragment extends ScanFragment<ShipmentDetailPresenter> implements ShipmentDetailContract.View {

    @BindView(R.id.tv_shipment_detail_productName)
    AutofitTextView tvShipmentDetailProductName;
    @BindView(R.id.tv_shipment_detail_productSpec)
    AutofitTextView tvShipmentDetailProductSpec;
    @BindView(R.id.tv_shipment_detail_manufacturer)
    TextView tvShipmentDetailManufacturer;
    @BindView(R.id.tv_shipment_detail_productCode)
    TextView tvShipmentDetailProductCode;
    @BindView(R.id.tv_shipment_detail_uom)
    TextView tvShipmentDetailUom;
    @BindView(R.id.tv_shipment_detail_lot)
    TextView tvShipmentDetailLot;
    @BindView(R.id.tv_shipment_detail_guaranteeDate)
    TextView tvShipmentDetailGuaranteeDate;
    @BindView(R.id.tv_shipment_detail_pickListId)
    TextView tvShipmentDetailpickListId;
    @BindView(R.id.tv_shipment_detail_receving)
    TextView tvShipmentDetailReceving;
    @BindView(R.id.tv_shipment_detail_qtyLeft)
    TextView tvShipmentDetailQtyLeft;
    @BindView(R.id.tv_shipment_detail_bpatName)
    TextView tvShipmentDetailBpatName;
    @BindView(R.id.tv_shipment_detail_qtyConfirmed)
    AppCompatEditText etShipmentDetailQtyPicked;
    @BindView(R.id.et_shipment_detail_qtyRejected)
    AppCompatEditText etRejected;
    @BindView(R.id.spinner_shipment_detail_locator)
    EditSpinner spinnerLocator;
    @BindView(R.id.bt_shipment_detail_ok)
    Button btShipmentDetailOk;
    @BindView(R.id.buttom_bar_group)
    LinearLayout buttomBarGroup;
    @BindView(R.id.bt_shipment_resume_lot)
    Button btResumeLot;
    private ShipmentBean shipmentBean;
    private static List<ShipmentBean> mShipmentBeans;
    private Locator locator;//设置的货位
    private ArrayList<Locator> locators;//所有货位
    private String barcodeData;
    private List<MonitorCode> monitorCodes = new ArrayList<>();
    public static ShipmentDetailFragment newInstance(ShipmentBean data) {
        ShipmentDetailFragment fragment = new ShipmentDetailFragment();
        fragment.shipmentBean = data;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerShipmentDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .commonModule(new CommonModule())
                .shipmentDetailModule(new ShipmentDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_shipment_detail, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.setTitleText(shipmentBean.getOrderTypeName() + "出库");
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l->{
            if(mPresenter.isError){
                setFragmentResult(RESULT_OK,new Bundle());
            }
            pop();
        });
        TextView rithtTextview = mCommonToolbar.getRightMenuView(0);
        rithtTextview .setText("下一个");
        rithtTextview.setOnClickListener(l->{
                    setFragmentResult(-2,null);
                    pop();
                });
        initViewData();
        initSpinner();

    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    private void initSpinner() {

        List<Locator> list = new ArrayList<>();//Arrays.asList("默认货位","理货货位","中药货位");
        spinnerLocator.setItemData(list);
        spinnerLocator.getEditText().setTextSize(15);
        spinnerLocator.setImageOnClickListener(new View.OnClickListener() {
            int i = 0;

            @Override
            public void onClick(View v) {
                if (i == 0) {
                    i++;

                }
            }
        });
        spinnerLocator.setOnItemClickListener((parent, view, position, id) -> locator = spinnerLocator.getSelectItem());

    }

    private void initViewData() {
        if("JN".equals(BuildConfig.TYPE)){
            btResumeLot.setVisibility(View.VISIBLE);
            btResumeLot.setOnClickListener(v->{

            });
        }
        assert shipmentBean != null;
        tvShipmentDetailProductName.setText(shipmentBean.getProductName());
        tvShipmentDetailProductSpec.setText(shipmentBean.getProductSpec());
        tvShipmentDetailManufacturer.setText(shipmentBean.getManufacturer());
        tvShipmentDetailProductCode.setText(shipmentBean.getProductCode());//不清楚 ？
        tvShipmentDetailUom.setText(shipmentBean.getUomName());
        tvShipmentDetailLot.setText(shipmentBean.getLot());
        tvShipmentDetailGuaranteeDate.setText(shipmentBean.getGuaranteeDate());
        tvShipmentDetailpickListId.setText((shipmentBean.getPickListId() + ""));
        tvShipmentDetailQtyLeft.setText((shipmentBean.getQtyLeft().intValue()+"" ));
        etShipmentDetailQtyPicked.setText((shipmentBean.getQtyLeft().intValue() + ""));
        tvShipmentDetailBpatName.setText(shipmentBean.getBpartnerName());
        etRejected.setText("0");
        if (shipmentBean.getFromLocatorValue() != null) {
            locator = new Locator(shipmentBean.getFromLocatorId(), shipmentBean.getFromLocatorValue(), shipmentBean.getFromLocatorValue());
            spinnerLocator.setText(shipmentBean.getFromLocatorValue());
        }
        //tvShipmentDetailReceving.setText(shipmentBean.get);

    }
    private void initEvent() {
        etShipmentDetailQtyPicked.addTextChangedListener(new TextWatcher() {
            String beforeText ;
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeText = s.toString();
            }


            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                doAfterTextChanged(s,beforeText,etShipmentDetailQtyPicked,etRejected);
            }
        });

        etRejected.addTextChangedListener(new TextWatcher() {
            String beforeText ;
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeText = s.toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                doAfterTextChanged(s,beforeText,etRejected,etShipmentDetailQtyPicked);
            }
        });
    }



    private void doAfterTextChanged(Editable s, String beforeText, EditText nowEdit, EditText newText) {
        String data = s.toString();
        if(nowEdit.hasFocus()&&!data.equals(beforeText)){

            try {
                BigDecimal received = new BigDecimal(0);
                if(!data.isEmpty()){
                    received =new BigDecimal(data);
                }
                BigDecimal number = shipmentBean.getQtyLeft().subtract(received);
                if(number.intValue() <0){
                    DialogUtil.showErrorDialog(getContext(),"已拣数量必须不能大于待拣数量！");
                    nowEdit.setText(beforeText);
                    return;
                }
                newText.setText(String.valueOf(number.intValue()));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }
    private MaterialDialog buder;
    private SuperInputEditText etSupervision;
    private MonitorCodeAdapter monitorCodeAdapter;
    boolean isScanSupervision = false;//是否是扫描监管码
    void initScanDialog(){

        monitorCodeAdapter = new MonitorCodeAdapter(monitorCodes);
        buder = new MaterialDialog.Builder(mContext)
                .title("监管码绑定")
                .titleGravity(GravityEnum.CENTER)
                .customView(R.layout.dialog_scan_ok, true)
                .positiveText("确认")
                //.negativeText("取消")
                .autoDismiss(false)
                .onAny((dialog, which) -> {
                    isScanSupervision = false;
                    if (which == DialogAction.POSITIVE) {
                        //pickListMaId:1212,monitoringCode:['1111','1234','4444']
                        JSONArray monitoringCode = new JSONArray();
                        for(MonitorCode m :monitorCodes){
                            if(m.getId()>0){
                                monitoringCode.add(m.getCode());
                            }

                        }
                        if(monitoringCode.size()>0){
                            JSONObject data = new JSONObject();
                            data.put("pickListMaId",shipmentBean.getPickListMaId());
                            data.put("monitoringCode",monitoringCode);
                            mPresenter.doConfirm(HttpMethodContains.SHIPMENT_CODE_CREATE,data, dialog::dismiss);
                        }

                    }else if (which == DialogAction.NEGATIVE) {
                        // Toast.makeText(MainActivity.this, "不同意", Toast.LENGTH_LONG).show();
                        monitorCodeAdapter.getData().clear();
                        monitorCodeAdapter.notifyDataSetChanged();

                    }
                    //
                })
                .build();


        //初始化Adapter
        RecyclerView recyclerView = buder.getCustomView().findViewById(R.id.rv_purchase_scan_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));

        ItemDragAndSwipeCallback mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(monitorCodeAdapter);
        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(recyclerView);
        OnItemDragListener listener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.WHITE);
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {

            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.BLACK);
            }
        };
        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
            private int position = -1;
            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
                position = pos;
            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            //删除item
            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
                //{pickListMaId:1212,monitoringCode:1111}
                if(pos!=-1){
                    position = pos;
                }
                MonitorCode  m = monitorCodes.get(position);
                if(m.getId() == 0){
                    JSONObject data = new JSONObject();
                    data.put("pickListMaId",shipmentBean.getPickListMaId());
                    data.put("monitoringCode",m.getCode());
                    mPresenter.doConfirm(HttpMethodContains.SHIPMENT_CODE_DELETE,data,()->{

                    });
                }
            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
                canvas.drawColor(ContextCompat.getColor(mContext, R.color.green));

            }
        };

        //mItemDragAndSwipeCallback.setDragMoveFlags(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN);
        mItemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.START | ItemTouchHelper.END);
        // 开启滑动删除
        monitorCodeAdapter.enableSwipeItem();
        monitorCodeAdapter.setOnItemSwipeListener(onItemSwipeListener);
        // 开启拖拽
        monitorCodeAdapter.enableDragItem(mItemTouchHelper);
        monitorCodeAdapter.setOnItemDragListener(listener);
        recyclerView.setAdapter(monitorCodeAdapter);
        Button button = buder.getCustomView().findViewById(R.id.button_scan_clear);
        button.setOnClickListener(l->{
            monitorCodeAdapter.getData().clear();
            monitorCodeAdapter.notifyDataSetChanged();
        });
        etSupervision = buder.getCustomView().findViewById(R.id.et_receiveScanCode_list_SerNo);
        etSupervision.setOnKeyListener((v, keyCode, event) -> {

            if (keyCode == KeyEvent.KEYCODE_ENTER && !etSupervision.getText().toString().isEmpty()) {

                addBindData();
                return true;
            } else {
                return false;
            }

        });

    }

    private void addBindData() {
        barcodeData = etSupervision.getText().toString();
        MonitorCode supervisionCode  =new MonitorCode(shipmentBean.getPickListMaId(),barcodeData);

        if (monitorCodeAdapter.getData().contains(supervisionCode)) {
            Toast.makeText(mContext, "绑定的数据重复！", Toast.LENGTH_LONG).show();
            return;
        }
        monitorCodeAdapter.addData(supervisionCode);

    }
    @OnClick({R.id.bt_shipment_detail_supervise, R.id.bt_shipment_detail_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_shipment_detail_supervise:
                isScanSupervision = true;
           /*     if(shipmentBean.getSupervisionCodes()!=null){
                    monitorCodeAdapter.getData().addAll(monitorCodes);
                }*/
                mPresenter.getMonitorCodes(shipmentBean.getPickListMaId(),list ->{
                    monitorCodes.clear();
                    monitorCodes.addAll(list);
                    monitorCodeAdapter.notifyDataSetChanged();
                });
                buder.show();
                break;
            case R.id.bt_shipment_detail_ok:
                //  DialogUtil.showMsgDialog(getContext(),"",shipmentBean.toString());
              /*  if (spinnerLocator.getText().isEmpty()) {
                    DialogUtil.showErrorDialog(getContext(), "请输入货位！");
                    return;
                }
                if (locator == null) {
                    JSONObject data = new JSONObject();
                    data.put("value", spinnerLocator.getText());
                    mPresenter.getLocators(data,list->{
                       locator = list.get(0);
                       doConfirm();

                    });
                } else {
                    doConfirm();
                }*/
                doConfirm();
                break;
        }
    }
    private void doConfirm() {

        JSONObject params = new JSONObject();

      /*  if("Y".equals(shipmentBean.getIsControlledProduct())) {
            ShipmentFragment fragment = (ShipmentFragment) getPreFragment();
            if (fragment != null && fragment.getUser() == null) {
                HttpClientHelper.showSelectSecondChangeDialog(getActivity(), (dialog, user) -> {
                    fragment.setUser(user);
                    params.put("workerId2", fragment.getUser().getId());
                    submit(params);
                });
                return;
            }
            params.put("workerId2", fragment.getUser().getId());
        }*/
        submit(params);

    }

    private void submit(JSONObject params) {
        JSONArray lineData = new JSONArray();
        params.put("pickListJobId", shipmentBean.getPickListJobId());
        params.put("qtyConfirm", etShipmentDetailQtyPicked.getText().toString());
        params.put("qtyCancel",etRejected.getText().toString());
        lineData.add(params);
        JSONObject data = new JSONObject();
        data.put("pickListId", shipmentBean.getPickListId());//任务
        data.put("lineData", lineData); //拣货数量
//        mPresenter.doConfirm(data,()->{
        assert mPresenter != null;
        mPresenter.pickComfirm(data, () -> {
            showMessage("处理成功");
            setFragmentResult(RESULT_OK, new Bundle());
            pop();
        });
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initEvent();

    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        if(isScanSupervision){
            etSupervision.setText(barcodeData);
            addBindData();
        }else{
            spinnerLocator.setText(barcodeData);
        }
    }
}
